// import React, { useState } from 'react'
import React from 'react'
import ReactDOM from 'react-dom'

/**
 * 自定义实现useState
 * @param {*初始值} initialState 
 */

let state = []
let setState = []
let stateIndex = 0

function creatStter (index) {
    return function (newState) {
        state[index] = newState
        console.log(state[index])
        render()
    }
}
function useState (initialState) {
    if(!state[stateIndex]){
        let index = stateIndex++
        state[index] = initialState
        setState[index] = creatStter(index)

        return [state[index], setState[index]]
    }

    const a = state[stateIndex];
    const b = setState[stateIndex];
    stateIndex++

    return [a, b]
}
// render() 的时候应该要考虑合并执行更新，否则会多次调用！假如说同时调用多个set方法时！
function render() {
    stateIndex = 0
    ReactDOM.render(<Hook />, document.getElementById('root'))
}


/**
 * 自定义实现useEffect
 * @param {*} callback 
 * @param {*} depsAry 
 */
function useEffect (callback, depsAry) {
    // 判断callback是不是函数

    // 判断depsAry是否传递

    // 判断depsAry是否数组
    // 获取上一次的状态值

    // 判断depsAry是否发生变化：有变化执行callback

    // 更新depsAry
}


function reducer (state, action) {
    switch(action.type){
        case 'increament': 
            return state + 1
        case 'decreament': 
            return state - 1
        default:
            return state
    }
}

/**
 * 自定义实现useReducer
 * @param {*} reducer 
 * @param {*} initialState 
 * @returns 
 */
function useReducer (reducer, initialState) {
    // 先拿到 state 和 setState
    const [state, setState] = useState(initialState)

    // 定义dispatch方法
    function dispatch (action) {
        const newState = reducer(state, action)
        setState(newState)
    }

    return [state, dispatch]
}

function Hook () {
    // useState
    const [name, setName] = useState('张三')
    const [age, setAge] = useState(18)

    // useEffect使用场景1：componentDidMount()、componentDidUpdate()
    // useEffect(()=>{
    //     console.log("componentDidMount()、componentDidUpdate()")
    // })

    // useEffect使用场景2：
    useEffect(()=>{
        console.log("name")
    }, [name])

    useEffect(()=>{
        console.log("age")
    }, [age])

    // useReducer
    const [count, dispatch] = useReducer(reducer, 0)

    return <div>
        <p>示例，测试hooks：</p>
        <p>{name}</p>
        <p>{age}</p>
        <p>
            <button onClick={()=>setName('李四')}>setName</button>
            <button onClick={()=>setAge(age+1)}>setAge</button>
        </p>
        <p>{count}</p>
        <p>
            <button onClick={()=>dispatch({type: 'increament'})}>increament</button>
            <button onClick={()=>dispatch({type: 'decreament'})}>decreament</button>
        </p>
    </div>
}


export default Hook